//
//  LTNSRunloopViewController.m
//  Total
//
//  Created by xin on 2017/7/3.
//  Copyright © 2017年 elephants. All rights reserved.
//

#import "LTNSRunloopViewController.h"
#import "LTRunloopCell.h"
#import "LTTimeModel.h"

@interface LTNSRunloopViewController () <UITableViewDelegate,UITableViewDataSource>
{
    NSTimer *tickTimer;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray * listArray;

@end

@implementation LTNSRunloopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(popCurrentViewController)];
    
    self.listArray = [NSMutableArray arrayWithCapacity:100];
    
    for (int i = 0; i < 100; i++) {
        LTTimeModel * model = [LTTimeModel ltTimeModelWithTitle:@"Time" countdownTime:@(300+i*10)];
        [self.listArray addObject:model];
    }

    [self runloopTest];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//让timer停止
- (void)popCurrentViewController
{
    
    [tickTimer invalidate];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)timerFire {
    
    __weak __typeof__(self) weakSelf = self;
    
    [self.listArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LTTimeModel * model = weakSelf.listArray[idx];
        [model countDown];
    }];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationRunloopCell object:nil];
}

- (void)runloopTest{
    
    tickTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerFire) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:tickTimer forMode:NSRunLoopCommonModes];
    [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
}

- (void)dealloc
{
    NSLog(@"%s",__func__);
}

#pragma mark tableview

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LTRunloopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LTRunloopCell" forIndexPath:indexPath];
    
    cell.model = self.listArray[indexPath.row];
    
    return cell;
}

@end
